#!/usr/bin/python
import sys
import XenAPI
import base64
import subprocess

path = "/home/nehal/Work/Repository/txtrepo/"

cfile  = path +"challange"
blob   = path + "temppub"
secret = path + "secretfile"
xenkey = path + "temp.key"
aik    = path + "outAik.key"
prg    = path + "aikchallenge"

#./aikchallenge secretfile temppub challange outAik.key

def doexec(args, inputtext=None):
    """Execute a subprocess, then return its return code, stdout and stderr"""
    proc = subprocess.Popen(args,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
    (stdout,stderr) = proc.communicate(inputtext)
    rc = proc.returncode
    return (rc,stdout,stderr)

def call_exec():
    (rc,stdout,stderr) = doexec([prg, secret,blob,xenkey,cfile,aik])
    return rc

def main(session):
    call_exec()
    host_ref = session.xenapi.session.get_this_host(session.handle)
    f = open(cfile,"r")
    challange =base64.b64encode(f.read())
    args = {"challange":challange}
    ret_val = session.xenapi.host.call_plugin(host_ref, 'txtverify', 'main', args)
    print ret_val

if __name__ == "__main__":
    if len(sys.argv) <> 4:
		print "Usage:"
		print sys.argv[0], "<XenServer host> <username> <password>"
		sys.exit(1)
    url = "https://" + sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]
    session = XenAPI.Session(url)
    session.xenapi.login_with_password(username, password)
    try:
        main(session)
    except Exception, e:
        print str(e)
        raise

